/***************************************************
File:           LPK_DispatchOnLineOfSight.cs
Authors:        Christopher Onorati
Last Updated:   8/1/2019
Last Version:   2018.3.14

Description:
  This component checks the LOS between two gameobjects.
  Note both gameobjects need to have colliders to be detected.

This script is a basic and generic implementation of its 
functionality. It is designed for educational purposes and 
aimed at helping beginners.

Copyright 2018-2019, DigiPen Institute of Technology
***************************************************/

using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace LPK
{

/**
* CLASS NAME  : LPK_DispatchOnLineOfSight
* DESCRIPTION : Check the line of sight between two objects with a raycast.
**/
public class LPK_DispatchOnLineOfSight : LPK_Component
{
    /************************************************************************************/

    [Tooltip("Object that is trying to look for others.  Defaults to self if left unset.  This is useful for prefab setup.")]
    [Rename("Source Game Object Transform")]
    public Transform m_pSource;

    [Tooltip("Game Objects the source is trying to find.")]
    public GameObject[] m_Targets;

    public float m_flDistance = Mathf.Infinity;

    [Tooltip("Layer mask to use for filtering.  Leave empty to collider with everything.")]
    [Rename("Layer Mask")]
    public LayerMask m_layerMask;

    [Header("Event Sending Info")]

    [Tooltip("Event sent when line of sight is established between the source and a target.")]
    public LPK_CollisionEventSendingInfo m_LineOfSightEstablishedEvent;

    [Tooltip("Event sent when line of sight is maintained between the source and a target.")]
    public LPK_CollisionEventSendingInfo m_LineOfSightMaintainedEvent;

    [Tooltip("Event sent when line of sight is lost between the source and the target it was detecting.")]
    public LPK_CollisionEventSendingInfo m_LineOfSightLostEvent;

    /************************************************************************************/

    //Stores currently found game objects.
    List<GameObject> m_pFoundObjects = new List<GameObject>();

    /**
    * FUNCTION NAME: Start
    * DESCRIPTION  : Sets up event detection for toggling active state.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void Start()
    {
        if (m_pSource == null)
            m_pSource = gameObject.transform;
    }

    /**
    * FUNCTION NAME: Update
    * DESCRIPTION  : Sends out raycasts to the objects we are trying to establish a line of sight for.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void Update()
    {
        for (int i = 0; i < m_Targets.Length; i++)
            CheckLOS(m_pSource, m_Targets[i].transform);
    }

    /**
    * FUNCTION NAME: CheckLOS
    * DESCRIPTION  : Tests LOS for each object we are tracking.
    * INPUTS       : _source - The object doing the looking.
    *                _target - The object the source is looking for.
    * OUTPUTS      : None
    **/
    void CheckLOS(Transform _source, Transform _target)
    {
        bool bCanSee = false;
        
        Vector3 dir = _target.position - _source.position;
        dir.Normalize();

        RaycastHit2D hit = Physics2D.Raycast(_source.position, dir, m_flDistance, m_layerMask);

        if (!hit.collider)
            return;

        //Epsilon of 0.05f
        if (hit.collider.gameObject == _target)
            bCanSee = true;

        //Target has been found
        if (bCanSee && !m_pFoundObjects.Find(obj => obj.name == _target.name))
            DispatchFoundEvent(_target.gameObject);

        else if (bCanSee && m_pFoundObjects.Find(obj => obj.name == _target.name))
            DispatchMaintainEvent(_target.gameObject);

        //Target has been lost.
        else if (!bCanSee && m_pFoundObjects.Find(obj => obj.name == _target.name))
            DispatchLostEvent(_target.gameObject);
    }

    /**
    * FUNCTION NAME: DispatchFoundEvent
    * DESCRIPTION  : Dispatches the established LOS event.
    * INPUTS       : _target - Game object to add to the found objects list.
    * OUTPUTS      : None
    **/
    void DispatchFoundEvent(GameObject _target)
    {
        //This object has been found.
        m_pFoundObjects.Add(_target);

        if (m_bPrintDebug)
            LPK_PrintDebug(this, "Line of sight established between " + m_pSource.name + " and " + _target);

        if(m_LineOfSightEstablishedEvent != null && m_LineOfSightEstablishedEvent.m_Event != null)
        {
            if(m_LineOfSightEstablishedEvent.m_EventSendingMode == LPK_CollisionEventSendingInfo.LPK_EventSendingMode.ALL)
                m_LineOfSightEstablishedEvent.m_Event.Dispatch(null);
            else if(m_LineOfSightEstablishedEvent.m_EventSendingMode == LPK_CollisionEventSendingInfo.LPK_EventSendingMode.OWNER)
                m_LineOfSightEstablishedEvent.m_Event.Dispatch(gameObject);
            else if (m_LineOfSightEstablishedEvent.m_EventSendingMode == LPK_CollisionEventSendingInfo.LPK_EventSendingMode.OTHER)
                m_LineOfSightEstablishedEvent.m_Event.Dispatch(_target);
            else if (m_LineOfSightEstablishedEvent.m_EventSendingMode == LPK_CollisionEventSendingInfo.LPK_EventSendingMode.TAGS)
                m_LineOfSightEstablishedEvent.m_Event.Dispatch(gameObject, m_LineOfSightEstablishedEvent.m_Tags);
        
            if (m_bPrintDebug)
                LPK_PrintDebug(this, "Established Line of Sight event dispatched");
        }
    }

    /**
    * FUNCTION NAME: DispatchMaintainEvent
    * DESCRIPTION  : Dispatches the maintained LOS event.
    * INPUTS       : _target - Object that was seen.  Only used for debug logging here.
    * OUTPUTS      : None
    **/
    void DispatchMaintainEvent(GameObject _target)
    {
        if (m_bPrintDebug)
            LPK_PrintDebug(this, "Line of sight maintained between " + m_pSource.name + " and " + _target);

        if(m_LineOfSightMaintainedEvent != null && m_LineOfSightMaintainedEvent.m_Event != null)
        {
            if(m_LineOfSightMaintainedEvent.m_EventSendingMode == LPK_CollisionEventSendingInfo.LPK_EventSendingMode.ALL)
                m_LineOfSightMaintainedEvent.m_Event.Dispatch(null);
            else if(m_LineOfSightMaintainedEvent.m_EventSendingMode == LPK_CollisionEventSendingInfo.LPK_EventSendingMode.OWNER)
                m_LineOfSightMaintainedEvent.m_Event.Dispatch(gameObject);
            else if (m_LineOfSightMaintainedEvent.m_EventSendingMode == LPK_CollisionEventSendingInfo.LPK_EventSendingMode.OTHER)
                m_LineOfSightMaintainedEvent.m_Event.Dispatch(_target);
            else if (m_LineOfSightMaintainedEvent.m_EventSendingMode == LPK_CollisionEventSendingInfo.LPK_EventSendingMode.TAGS)
                m_LineOfSightMaintainedEvent.m_Event.Dispatch(gameObject, m_LineOfSightMaintainedEvent.m_Tags);
        
            if (m_bPrintDebug)
                LPK_PrintDebug(this, "Established Line of Sight event dispatched");
        }
    }

    /**
    * FUNCTION NAME: DispatchFoundEvent
    * DESCRIPTION  : Dispatches the lost LOS event.
    * INPUTS       : _target - Game object to remove from the found objects list.
    * OUTPUTS      : None
    **/
    void DispatchLostEvent(GameObject _target)
    {
        //This object has been lost.
        m_pFoundObjects.Remove(_target);

        if (m_bPrintDebug)
            LPK_PrintDebug(this, "Line of sight lost between " + m_pSource.name + " and " + _target);

        if(m_LineOfSightLostEvent != null && m_LineOfSightLostEvent.m_Event != null)
        {
            if(m_LineOfSightLostEvent.m_EventSendingMode == LPK_CollisionEventSendingInfo.LPK_EventSendingMode.ALL)
                m_LineOfSightLostEvent.m_Event.Dispatch(null);
            else if(m_LineOfSightLostEvent.m_EventSendingMode == LPK_CollisionEventSendingInfo.LPK_EventSendingMode.OWNER)
                m_LineOfSightLostEvent.m_Event.Dispatch(gameObject);
            else if (m_LineOfSightLostEvent.m_EventSendingMode == LPK_CollisionEventSendingInfo.LPK_EventSendingMode.OTHER)
                m_LineOfSightLostEvent.m_Event.Dispatch(_target);
            else if (m_LineOfSightLostEvent.m_EventSendingMode == LPK_CollisionEventSendingInfo.LPK_EventSendingMode.TAGS)
                m_LineOfSightLostEvent.m_Event.Dispatch(gameObject, m_LineOfSightLostEvent.m_Tags);
        
            if (m_bPrintDebug)
                LPK_PrintDebug(this, "Established Line of Sight event dispatched");
        }
    }
}

#if UNITY_EDITOR

[CustomEditor(typeof(LPK_DispatchOnLineOfSight))]
public class LPK_DispatchOnLineOfSightEditor : Editor
{
    SerializedProperty source;
    SerializedProperty ctargets;
    SerializedProperty layerMask;

    SerializedProperty lineOfSightEstablishedReceivers;
    SerializedProperty lineOfSightMaintainedReceivers;
    SerializedProperty lineOfSightLostReceivers;

    /**
    * FUNCTION NAME: OnEnable
    * DESCRIPTION  : Save out serialized classes.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void OnEnable()
    {
        source = serializedObject.FindProperty("m_pSource");
        ctargets = serializedObject.FindProperty("m_Targets");
        layerMask = serializedObject.FindProperty("m_layerMask");

        lineOfSightEstablishedReceivers = serializedObject.FindProperty("m_LineOfSightEstablishedEvent");
        lineOfSightMaintainedReceivers = serializedObject.FindProperty("m_LineOfSightMaintainedEvent");
        lineOfSightLostReceivers = serializedObject.FindProperty("m_LineOfSightLostEvent");
    }

    /**
    * FUNCTION NAME: OnInspectorGUI
    * DESCRIPTION  : Override GUI for inspector.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    public override void OnInspectorGUI()
    {
        LPK_DispatchOnLineOfSight owner = (LPK_DispatchOnLineOfSight)target;

        LPK_DispatchOnLineOfSight editorOwner = owner.GetComponent<LPK_DispatchOnLineOfSight>();

        EditorGUI.BeginDisabledGroup(true);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel("Script");
        editorOwner = (LPK_DispatchOnLineOfSight)EditorGUILayout.ObjectField(editorOwner, typeof(LPK_DispatchOnLineOfSight), false);
        GUILayout.EndHorizontal();
        EditorGUI.EndDisabledGroup();

        //Undo saving.
        Undo.RecordObject(owner, "Property changes on LPK_DispatchOnLineOfSight");

        GUILayout.Space(10);
        EditorGUILayout.LabelField("Component Properties", EditorStyles.boldLabel);

        EditorGUILayout.PropertyField(source, true);
        LPK_EditorArrayDraw.DrawArray(ctargets, LPK_EditorArrayDraw.LPK_EditorArrayDrawMode.DRAW_MODE_BUTTONS);
        owner.m_flDistance = EditorGUILayout.FloatField(new GUIContent("Search Distance", "How far to look for an object.  By default, look forever."), owner.m_flDistance);
        EditorGUILayout.PropertyField(layerMask, true);

        //Events
        EditorGUILayout.PropertyField(lineOfSightEstablishedReceivers, true);
        EditorGUILayout.PropertyField(lineOfSightMaintainedReceivers, true);
        EditorGUILayout.PropertyField(lineOfSightLostReceivers, true);

        //Debug properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Debug Properties", EditorStyles.boldLabel);

        owner.m_bPrintDebug = EditorGUILayout.Toggle(new GUIContent("Print Debug Info", "Toggle console debug messages."), owner.m_bPrintDebug);
        owner.m_sLabel = EditorGUILayout.TextField(new GUIContent("Label", "Notes for the user about this component.  This does nothing to the game or build."), owner.m_sLabel);

        //Apply changes.
        serializedObject.ApplyModifiedProperties();
    }
}

#endif  //UNITY_EDITOR

}   //LPK
